package io.p2p.stream.dispatch.service;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.DatagramPacket;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.p2p.stream.dispatch.handler.DispatchUdpServerHandler;
import org.slf4j.LoggerFactory;
import org.slf4j.Logger;

import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;


public class DispatchUdpServer {

    private Logger log = LoggerFactory.getLogger(DispatchUdpServer.class);
    private String host;

    private int port;

    private EventLoopGroup bossGroup;

    private Bootstrap bootstrap;

    private Channel channel;

    public Channel getChannel(){
        return channel;
    }

    public DispatchUdpServer() {

    }

    public void start(String host, int port) {
        ChannelFuture future = null;
        try {
            bossGroup = new NioEventLoopGroup();
            bootstrap = new Bootstrap();
            bootstrap.group(bossGroup)
                    .channel(NioDatagramChannel.class)
                    .option(ChannelOption.SO_BROADCAST, true)
                    .handler(new DispatchUdpServerHandler());

            future = bootstrap.bind(host, port).sync();
            channel = future.channel();

            log.info("P2P UDP Server started on ip: {}, port: {}", host, port);

            this.host = host;
            this.port = port;
        } catch (InterruptedException e) {
            log.error("Failed to start P2P UDP Server: {}", e.getMessage());
            return;
        }

        final ChannelFuture finalFuture = future;
        Thread listenerThread = new Thread(()->{
            if(finalFuture != null){
                try {
                    finalFuture.channel().closeFuture().sync();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                } finally{
                    bossGroup.shutdownGracefully();
                }
            }
        });
        listenerThread.start();
    }

    public void shutdown(){
        bossGroup.shutdownGracefully();
    }

    public void send(String msg, InetSocketAddress remoteAddress){
        channel.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer(msg, StandardCharsets.UTF_8),
                remoteAddress));
    }
}
